<template>
  <view class="settings-container">
    <!-- 设置选项列表 -->
    <view class="menu-list">
      <!-- 个人资料 -->
      <view class="menu-item" @click="navigateToProfile">
        <text class="menu-text">个人资料</text>
        <up-icon name="arrow-right" color="#999"></up-icon>
      </view>

      <!-- 关于我们 -->
      <view class="menu-item" @click="showAboutModal = true">
        <text class="menu-text">关于我们</text>
        <up-icon name="arrow-right" color="#999"></up-icon>
      </view>

      <view class="menu-item" @click="selectFile">
        <text class="menu-text">基础数据导入</text>
        <up-icon name="arrow-right" color="#999"></up-icon>
      </view>

      <!-- 到期日期 -->
      <view class="menu-item">
        <text class="menu-text">到期日期</text>
        <text class="expiry-date">2025-12-24</text>
      </view>

      <view class="menu-item">
        <text class="menu-text">版本号</text>
        <text class="expiry-date">{{APP_VERSION}}</text>
      </view>
    </view>

    <!-- 退出登录按钮 -->
    <view class="logout-btn">
      <up-button type="error" plain @click="handleLogout">{{ $t('setting.logout') }}</up-button>
    </view>
    <!-- 关于我们弹窗 -->
    <up-modal
      :show="showAboutModal"
      title="关于我们"
      :closeOnClickOverlay="true"
      @close="showAboutModal = false"
      :showCancelButton="false"
      confirmText="确定"
      @confirm="showAboutModal = false"
    >
      <view class="about-content">
        <view class="company-name">安泰智和</view>

        <view class="section">
          <view class="section-title">公司简介</view>
          <view class="section-content">
            安泰智和科技有限公司是一家专注于企业资产管理解决方案的高新技术企业，成立于2014年04月01日。我们致力于为企业提供智能化、数字化的资产管理工具。
          </view>
        </view>

        <view class="section">
          <view class="section-title">联系我们</view>
          <view class="contact-info">
            <view>电话：13316870909</view>
            <view>邮箱：Liuhongtao@antaicloud.com</view>
            <view>地址：深圳市龙岗区龙岗街道怡丰路34号3栋311</view>
          </view>
        </view>
      </view>
    </up-modal>
  </view>
</template>

<script setup>
import { ref } from 'vue';
import fileSys from '@/utils/fileSys';
import { onLoad } from '@dcloudio/uni-app';
import http from '@/api/request';
import {APP_VERSION} from "@/utils/version";

const showAboutModal = ref(false);

const sheetFieldMap = ref({
  资产列表: {
    field: 'data',
    menuCode: 'assetlist',
    pageCode: 'assetimport',
    pageId: '',
    columns: {
      资产分类名称: 'asset_category',
      资产名称: 'asset_name',
      资产品牌: 'brand',
      规格型号: 'spec_model',
      标签编码: 'label_number',
      标签类型: 'tag_type',
      标签类型: 'tag_type',
      资产来源: 'asset_source',
      存放位置: 'location',
      计量单位: 'unit',
      采购日期: 'purchase_date',
      采购价格: 'purchase_price',
      净残值: 'asset_salvage_value',
      净残值: 'asset_salvage_value',
      备注: 'remark',
      SN码: 'sn_code',
      供应商: 'supplier',
      图片: 'image'
    }
  }
});

onLoad(async () => {
  // 获取页面信息
  await getPageInfo();
});

// 处理退出登录
const handleLogout = () => {
  uni.showModal({
    title: '提示',
    content: '确定要退出登录吗？',
    confirmText: '退出',
    cancelText: '取消',
    success: res => {
      if (res.confirm) {
        uni.removeStorageSync('token');
        uni.removeStorageSync('userInfo');
        uni.reLaunch({
          url: '/pages/login/login'
        });
      }
    }
  });
};

// 跳转到个人资料页
const navigateToProfile = () => {
  uni.navigateTo({
    url: '/pages/user/profile'
  });
};

const getPageInfo = async () => {
  const map = sheetFieldMap.value;
  const sheetNames = Object.keys(map);

  const requests = sheetNames.map(sheetName => {
    const item = map[sheetName];
    const { menuCode, pageCode } = item;

    const data = {
      menuCode,
      pageCode
    };

    console.log(data, 'data');
    return http.post('/api/page/GetPageInfoByCode', data).then(res => ({
      sheetName,
      res
    }));
  });

  const results = await Promise.all(requests);

  results.forEach(({ sheetName, res }) => {
    const { code, isSuccess, result } = res;
    if (code && isSuccess && result?.page?.parentPageId) {
      sheetFieldMap.value[sheetName].pageId = result.page.parentPageId;
    }
  });
};

const mapAssetData = (columns, rawData) => {
  return rawData.map(row => {
    const mappedRow = {};
    for (const [chineseKey, targetKey] of Object.entries(columns)) {
      mappedRow[targetKey] = row[chineseKey] || '';
    }
    return mappedRow;
  });
};

const selectFile = () => {
  fileSys().then(async res => {
    if (res.length) {
      uni.showLoading({
        title: '解析中...',
        mask: true
      });

      const sheetIndexes = Object.keys(sheetFieldMap.value);
      // 创建请求任务
      const requests = sheetIndexes.map((sheetIndex, i) => {
        const params = {
          pageId: sheetFieldMap.value[sheetIndex].pageId,
          params: {
            args: [
              { name: 'fileId', value: res[0].id },
              { name: 'columnIndex', value: 0 },
              { name: 'startIndex', value: 1 },
              { name: 'sheetIndex', value: i }
            ]
          },
          methodName: 'getUploadExcelFileData'
        };
        return http.post('/api/module/Invoke', params);
      });

      // 并发执行所有请求
      const responses = await Promise.all(requests);

      const finalData = {
        pageCode: 'basedataimport',
        params: {
          args: [
            {
              name: 'interfaceCode',
              value: 'Basedataimport.simplifyImport'
            }
          ]
        },
        methodName: 'simplifyImport'
      };

      sheetIndexes.forEach((sheetIndex, i) => {
        const { code, isSuccess, result } = responses[i];
        if (isSuccess && code && result.length > 0) {
          const field = sheetFieldMap.value[sheetIndex].field;
          const columns = sheetFieldMap.value[sheetIndex].columns;

          // 动态替换字段
          const mappedData = mapAssetData(columns, result);

          finalData.params.args.push({
            name: field,
            value: mappedData
          });
        }
      });
      try {
        const { code, success, error } = await http.post('/api/module/Invoke', finalData);
        if (code && success) {
          uni.hideLoading();
          uni.showToast({
            title: '导入成功',
            icon: 'success'
          });
        } else {
          uni.hideLoading();
          uni.showToast({
            title: error,
            icon: 'error'
          });
        }
      } catch (error) {
        uni.hideLoading();
        uni.showToast({
          title: error,
          icon: 'error'
        });
      }
    }
  });
};
</script>

<style lang="scss" scoped>
.settings-container {
  padding: 20rpx 30rpx;
  background-color: #f7f7f7;
  min-height: 100vh;
}

.header {
  padding: 30rpx 0;

  .title {
    font-size: 40rpx;
    font-weight: bold;
    color: #333;
  }
}

.menu-list {
  background-color: #fff;
  border-radius: 16rpx;
  overflow: hidden;
  margin-top: 30rpx;
}

.menu-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 30rpx;
  border-bottom: 1rpx solid #f5f5f5;

  &:last-child {
    border-bottom: none;
  }

  .menu-text {
    font-size: 32rpx;
    color: #333;
  }

  .expiry-date {
    font-size: 28rpx;
    color: #999;
  }
}

.logout-btn {
  margin-top: 60rpx;
  padding: 0 30rpx;

  :deep(.up-button) {
    height: 90rpx;
    line-height: 90rpx;
    font-size: 32rpx;
  }
}

.about-content {
  padding: 20rpx;

  .company-name {
    font-size: 36rpx;
    font-weight: bold;
    text-align: center;
    margin-bottom: 30rpx;
    color: #2979ff;
  }

  .section {
    margin-bottom: 30rpx;

    .section-title {
      font-size: 32rpx;
      font-weight: bold;
      margin-bottom: 15rpx;
      color: #333;
    }

    .section-content {
      font-size: 28rpx;
      color: #666;
      line-height: 1.6;
    }

    .contact-info {
      font-size: 28rpx;
      color: #666;
      line-height: 1.8;
    }
  }
}
</style>
